# Maintainer: David Runge <dvzrv@archlinux.org>

_name=PyMuPDF
pkgname=python-pymupdf
pkgver=1.23.6
pkgrel=3
pkgdesc="Python bindings for MuPDF's rendering library"
arch=(loong64 x86_64)
url="https://github.com/pymupdf/PyMuPDF"
license=(AGPL-3.0-or-later)
depends=(
  glibc
  libmupdf
  python
)
makedepends=(
  python-build
  python-distro
  python-installer
  python-setuptools
  python-wheel
  swig
  systemd
)
checkdepends=(
  python-fonttools
  python-pillow
  python-pytest
)
optdepends=(
  'python-fonttools: for building font subsets using fontTools'
  'python-pillow: for image file saving using pillow'
)
source=(
  $_name-$pkgver.tar.gz::$url/archive/refs/tags/$pkgver.tar.gz
  $pkgname-1.23.5-tesseract_tessdata_dir.patch
)
sha512sums=('7cdd7105f91c7f01839ce4291521bff1534cd7eb99ec506b56fa7b39afaf83a90ef77a2988cd3d710a8c9e273fda6427c367644e2b58459a8ab57eaa362de1d7'
            '849ace7d68e9060f057c1229f2cbfc43f418e761032d821ab50072cef7d32a5e821c2f58bcc16ba78b61d5eb2fbc042d8908c2c7d78b436fe40147e8121a1426')
b2sums=('dc78b7e85ec9d527d1fd40b8b3be5737fc1c5f9976b39a61ac104bbe210eb41d39ac66df03443383470d5c06f6afbaf9f3e39aebaf3f6b961f994763f3cc9842'
        '6f662ba8175c1960ba0d323cecef25fc283d1dd8f6a5af541bf13df52c2432f76841233389c35ea02182d8543231835cff30f03a2ae9eb231e1165cc83268b65')

prepare() {
  # remove bundled mupdf sources
  rm -frv $pkgname/*.tgz
  # we package clang and swig and don't need python-clang or python-swig
  sed -e 's/"libclang", "swig", //' -i $_name-$pkgver/pyproject.toml
  # fix tessdata location
  patch -Np1 -d $_name-$pkgver -i ../$pkgname-1.23.5-tesseract_tessdata_dir.patch
}

build() {
  local cflags=(
    -I/usr/include
    -I/usr/include/freetype2
    -I/usr/include/harbuzz
    -I/usr/include/mupdf
  )
  local ldflags=(
    -lfreetype
    -lgumbo
    -lharfbuzz
    -ljbig2dec
    -ljpeg
    -lleptonica
    -lmupdf
    -lopenjp2
    -ltesseract
  )

  cd $_name-$pkgver
  # build against system libmupdf
  export PYMUPDF_SETUP_MUPDF_BUILD=''
  # do not build against mupdfs (non-integrated) C++ API: https://github.com/pymupdf/PyMuPDF/issues/2628
  export PYMUPDF_SETUP_IMPLEMENTATIONS=a
  CFLAGS+=" ${cflags[@]}"
  LDFLAGS+=" ${ldflags[@]}"

  python -m build --wheel --no-isolation
}

check() {
  local pytest_options=(
    -vv
    # disable broken test, that upstream is not interested in fixing or disabling: https://github.com/pymupdf/PyMuPDF/issues/2127
    --deselect tests/test_pixmap.py::test_color_count
  )
  local _site_packages=$(python -c "import site; print(site.getsitepackages()[0])")

  cd $_name-$pkgver
  python -m installer --destdir=test_dir dist/*.whl
  export PYTHONPATH="$PWD/test_dir/$_site_packages:$PYTHONPATH"
  pytest "${pytest_options[@]}" tests/
}

package() {
  depends+=(
    freetype2 libfreetype.so
  )

  cd $_name-$pkgver
  python -m installer --destdir="$pkgdir" dist/*.whl
  install -vDm 644 README.md -t "$pkgdir/usr/share/doc/$pkgname/"
}
